package com.crocodileQ.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crocodileQ.common.AppException;
import com.crocodileQ.common.PageResult;
import com.crocodileQ.common.R;
import com.crocodileQ.constants.SystemConstants;
import com.crocodileQ.domain.DTO.ChildrenDTO;
import com.crocodileQ.domain.VO.CommentChildVO;
import com.crocodileQ.domain.VO.CommentVO;
import com.crocodileQ.domain.entity.Comment;
import com.crocodileQ.domain.entity.User;
import com.crocodileQ.enums.AppExceptionMsgEnum;
import com.crocodileQ.mapper.CommentMapper;
import com.crocodileQ.service.CommentService;
import com.crocodileQ.service.UserService;
import com.crocodileQ.utils.BeanCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * (Comment)表服务实现类
 *
 * @author makejava
 * @since 2024-01-02 20:56:54
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private UserService userService;

    /**
     * 分页查询文章评论
     *
     * @param commentType
     * @param articleId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public R<PageResult<CommentVO>> commentList(String commentType, Long articleId, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        //对articleId进行判断,当评论类型是文章时。
        queryWrapper.eq(SystemConstants.ARTICLE_COMMENT.equals(commentType),Comment::getArticleId,articleId);
        //根评论 rootId为-1,
        queryWrapper.eq(Comment::getRootId, SystemConstants.ROOT_ID);
        //根据type查询评论
        queryWrapper.eq(Comment::getType,commentType);
        queryWrapper.orderByDesc(Comment::getCreateTime);

        //分页查询评论
        Page<Comment> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);

        //封装CommentVO返回
        List<CommentVO> commentVOS = toCommentVOList(page.getRecords());


        //给所有的评论设置子评论
        for (CommentVO commentVO : commentVOS) {
            //获取子评论
            List<CommentVO> children = getChildren(commentVO.getId());
            ChildrenDTO childrenDTO = new ChildrenDTO();

            //查询子评论的条数
            //根据评论id查询，子评论
            LambdaQueryWrapper<Comment> queryChild = new LambdaQueryWrapper<>();
            queryChild.eq(Comment::getRootId,commentVO.getId());
            int total = (int) count(queryChild);

            childrenDTO.setChildren(children);
            childrenDTO.setTotal(total);



            //给评论匹配对应子评论
            commentVO.setChildren(childrenDTO);

        }

        return R.success(new PageResult<>(commentVOS,page.getTotal()));
    }

    /**
     * 保存评论
     * @param comment
     * @return
     */
    public R addComment(Comment comment) {
        //评论处理
        if(!StringUtils.hasText(comment.getContent())){
            throw new AppException(AppExceptionMsgEnum.CONTENT_NOT_NULL);
        }
        //保存评论信息
        save(comment);
        return R.success("保存成功");

    }

    /**
     * 获取子评论
     * @param id
     * @return
     */
    private List<CommentVO> getChildren(Long id) {
        //根据评论id查询，子评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getRootId,id);
        queryWrapper.orderByAsc(Comment::getCreateTime);

        List<Comment> comments = list(queryWrapper);


        return toCommentVOList(comments);

    }


    /**
     * 获取CommentVO
     * @param list
     * @return
     */
    private List<CommentVO> toCommentVOList(List<Comment> list){
        List<CommentVO> commentVOS = BeanCopyUtil.copyBeanList(list, CommentVO.class);

        //遍历commentVOS
        for (CommentVO commentVO : commentVOS) {
            //通过createBy查询用户的昵称、头像并赋值
            User userInfo = userService.getById(commentVO.getCreateBy());

            commentVO.setUserName(userInfo.getNickName());
            commentVO.setAvatar(userInfo.getAvatar());

            //通过toCommentUserId查询用户昵称并赋值
            //如果toCommentUserId不为-1才进行查询
            if(commentVO.getToCommentUserId() != SystemConstants.ROOT_ID){
                userInfo = userService.getById(commentVO.getToCommentUserId());
                //设置当前评论的根评论的用户名
                commentVO.setToCommentUserName(userInfo.getNickName());
                //当前评论人的头像
                userInfo = userService.getById(commentVO.getCreateBy());
                commentVO.setAvatar(userInfo.getAvatar());
            }

        }

        return commentVOS;
    }



}

